package com.sakiko.dailynote.utils;

import com.sakiko.dailynote.pojo.MinioProperties;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * projectName: com.itheima.skybigevent.utils
 *
 * @author: Yang
 * description: minio 工具类
 * time: 2025/8/14 21:42
 */

@Component
public class MinioUtil {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    MinioClient minioClient;

    public String uploadFile(String objectName, InputStream inputStream) throws Exception {
        String bucketName = minioProperties.getBucketName();
        
        try {
            // 检查桶是否存在，如果不存在则创建
            boolean exists = minioClient.bucketExists(
                BucketExistsArgs.builder().bucket(bucketName).build()
            );
            
            if (!exists) {
                minioClient.makeBucket(
                    MakeBucketArgs.builder().bucket(bucketName).build()
                );

                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(createBucketPolicyConfig(bucketName)).build());
            }
            
            // 上传文件
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, inputStream.available(), -1)
                    .build()
            );
            
            // 生成访问 URL
            String endpoint = minioProperties.getEndpoint();
            String url = endpoint + "/" + bucketName + "/" + objectName;
            
            return url;
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    // bucket 授权策略
    private String createBucketPolicyConfig(String bucketName) {
        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}
